package com.dfd.shiro.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    //声明自定义属性
    @Autowired
    private MyRealm myRealm;

    @Bean
    //自定义配置SecurityManager对象
    public DefaultWebSecurityManager defaultWebSecurityManager() {
        //创建DefaultWebSecurityManager对象
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //创建密码凭证匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(2);
        //设置密码凭证器存储到realm里
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        //设置自定义realm
        defaultWebSecurityManager.setRealm(myRealm);
        //设置CookieManager
        defaultWebSecurityManager.setRememberMeManager(cookieRememberMeManager());
        //返回
        return defaultWebSecurityManager;

    }

    /**
     * 记住我
     */
    public CookieRememberMeManager cookieRememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(cookie());
        //设置加密
        cookieRememberMeManager.setCipherKey(Base64.decode("3AvVhmFLUs0KTA3Kprsdag=="));
        return cookieRememberMeManager;
    }

    /**
     * cookie属性设置
     */
    public SimpleCookie cookie() {
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(60 * 3600 * 24);
        cookie.setPath("/");
        return cookie;
    }

    //配置shiro的过滤器放行
    @Bean
    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition() {
        //创建shiro的过滤器管理对象
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        //设置拦截和放行
        //设置放行的静态资源
        definition.addPathDefinition("/userController/login", "anon");
        definition.addPathDefinition("/userController/userLogin", "anon");


        definition.addPathDefinition("/js/**", "anon");
        definition.addPathDefinition("/resources/**", "anon");
        definition.addPathDefinition("/login.html", "anon");


        definition.addPathDefinition("/logout", "logout");
        definition.addPathDefinition("/**", "user");
        return definition;
    }

}
